/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package queenb.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.*;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.Cipher;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import queenb.net.entitybean.*;
import queenb.web.crm.store.CustomerStore;
import queenb.web.inteface.Q100Inf;
import queenb.web.store.ContactStore;
import queenb.web.store.M650Store;
import queenb.web.store.N350Store;
import queenb.web.store.Q100Store;
import queenb.web.util.Crypto;
import queenb.web.util.ResourcesProvider;
import queenb.web.util.Util;
import queenb.web.store.*;
import queenb.web.util.SessionProvider;

/**
 *
 * @author Nguyen Hung
 */
public class Q100Controller extends QueenbController {

    public static boolean flagCheckUser = false;
    private String message;
    private String fomatdate;
    private String language;
    private String timezone;
    private String money;
    private static String userLoginCheckTrue;
    private Q100Inf q100Inf;
    private String userLogin;
    private String passowrd;
    private String passwordCurrent;
    private String repassword;
    private int pn100;
    private List<Q100> listQ100;
    private Q100Store q100Store;
    private String avatar;// Avatar
    private int pm650;
    private int test;
    private String qv117;
    private String qv118;
    private String qv119;
    private String qv120;
    private String qv121;
    //Q000
    private int FN100;
    private int PQ000;
    private String QV001;//email
    private String QV002;//pass

    public Q100Controller() {
        Object pn100A = getRequest().getParameter("pn100");
        Object pn100M = getRequest().getParameter("fn100M");
        //   Object pnPM650 = getRequest().getParameter("pm650");
        if (pn100A != null) {
            this.pn100 = Integer.parseInt(pn100A.toString());
            listQ100 = getListTabQ100();
        }
        if (pn100M != null) {
            this.pn100 = Integer.parseInt(pn100M.toString());
            listQ100 = getListTabQ100();
        }
        if (getLoginSession().getLogin() != null) {
            if (pn100M == null && pn100A == null) {
                this.pn100 = getLoginSession().getLogin().getId();
            }
        }

        //process for Q000
//        actionQ000
//        idQ000
//        pn100Q000
        Object objactionQ000 = getRequest().getParameter("actionQ000");
        Object objidQ000 = getRequest().getParameter("idQ000");
        Object objpn100Q000 = getRequest().getParameter("pn100Q000");
        System.out.print("D:- objactionQ000: " + objactionQ000 + "  objidQ000: " + objidQ000 + "  objpn100Q000: " + objpn100Q000);

        if (objactionQ000 != null) {
            String objactionQ000str = objactionQ000.toString().trim();
            if (objactionQ000str.equals("add")) {
                this.PQ000 = 0;
            } else if (objactionQ000str.equals("edit")) {
                if (objidQ000 != null) {
                    try {
                        this.PQ000 = Integer.parseInt(objidQ000.toString());
                        getQ000ById(PQ000);
                    } catch (Exception e) {
                    }
                }
            }
        }

    }

    public void getQ000ById(int pq000) {
        Q000Store q000Store = new Q000Store();
        List<Q000> lst = q000Store.getListQ000(getLogin().getModule(), getLogin().getCompanyNo(), getLogin().getId(), getLogin().getUserName());
        if (lst != null) {
            System.out.println("D:- list getListAllQ000ByIDofMyprofile: " + lst.size());
        } else {
            System.out.println("D:- list getListAllQ000ByIDofMyprofile: null");
        }
        for (Q000 q000 : lst) {
            if (q000.getPQ000() == pq000) {
                this.QV001 = q000.getQV001();
                this.QV002 = q000.getQV002();
            }
        }
    }

    public void checkUserLogin() {
        int checkUser = q100Inf.checkLoginExist(userLogin);
        if (checkUser == 0) {
            setMessage("OK");
            this.userLoginCheckTrue = userLogin;
            flagCheckUser = true;
        } else {
            setMessage("NoOK");
            this.userLoginCheckTrue = "";
            flagCheckUser = false;
        }


    }

    public void updateQ100ByID() {
        if (pn100 > 0) {

            q100Store = new Q100Store();
            //int result = q100Store.updateQ100By(pn100, 0, 2, 3, 1, 2, 10, null, getUserLoginCheckTrue(), Util.convertMD5(this.passowrd), Util.toSQLDate(new Date()), Util.toSQLDate(new Date()), null, null, null, null, null, 0, 0, 0, 0, this.timezone, this.language, this.fomatdate, getLogin().userName);
            int result = q100Store.updateQ100By(pn100, 0, 2, 3, 1, 2, 10, null, getUserLoginCheckTrue(), "e99a18c428cb38d5f260853678922e03", Util.toSQLDate(new Date()), Util.toSQLDate(new Date()), null, null, null, null, this.money, 0, 0, 0, 0, this.timezone, this.language, this.fomatdate, getLogin().getModule(), getLogin().userName);
            showGlobalReport(true, getResourceString("datasavesuccessful"));
        } else {
            int result = q100Store.updateQ100By(pn100, 0, 2, 3, 1, 2, 10, null, getUserLoginCheckTrue(), Util.convertMD5(this.passowrd), Util.toSQLDate(new Date()), Util.toSQLDate(new Date()), null, null, null, null, null, 0, 0, 0, 0, this.timezone, this.language, this.fomatdate, getLogin().getModule(), getLogin().userName);
            System.out.println("không có");
            showGlobalReport(true, getResourceString("datasuccessfail"));
        }

        sendRedirectUrlTab("myprofile.jsp?fn100M=" + pn100 + "&linkfref=" + Util.convertMD5(getRequest().getRequestURI()));
    }

    public List<N350> getListAllN350ByIDofMyprofile() {

        try {
            N350Store n350Store = new N350Store();
            List<N350> lst = n350Store.findN350All(7, 99, 0, getLogin().getId(), 0, getLogin().getUserName());
            System.out.println("00------> size CMND" + lst.size());


            return lst;
        } catch (Exception ex) {
            System.out.println(ex);
            return null;
        }

    }

    public List<N950> getListAllN950ByIDofMyprofile() {

        try {
            ContactStore n950Store = new ContactStore();
            List<N950> lst = n950Store.getListContact(getLogin().getId(), 0, getLogin().getUserName());
            return lst;
        } catch (Exception ex) {
            System.out.println(ex);
            return null;
        }

    }

    public List<Q000> getListAllQ000ByIDofMyprofile() {

        try {
            Q000Store q000Store = new Q000Store();
            List<Q000> lst = q000Store.getListQ000(getLogin().getModule(), getLogin().getCompanyNo(), getLogin().getId(), getLogin().getUserName());
            if (lst != null) {
                System.out.println("D:- list getListAllQ000ByIDofMyprofile: " + lst.size());
            } else {
                System.out.println("D:- list getListAllQ000ByIDofMyprofile: null");
            }

            return lst;

        } catch (Exception ex) {
            System.out.println("Error from getListAllQ000ByIDofMyprofile: " + ex);
            return null;
        }

    }

    public int checkMail(String user, String password) {
        final String SMTP_AUTH_USER = user;
        final String SMTP_AUTH_PWD = password;
        final String SMTP_HOST_NAME = "smtp.gmail.com";
        final int SMTP_HOST_PORT = 465;
        int result = 0;
        try {
            if (SMTP_AUTH_USER.contains("@yahoo.com") || SMTP_AUTH_USER.contains("@ymail.com")) {
                String host, port;
                Properties props = System.getProperties();
                Session l_session = null;
                host = "smtp.mail.yahoo.com";
                port = "587";

                props.put("mail.smtp.host", host);
                props.put("mail.smtp.auth", "true");
                props.put("mail.debug", "false");
                props.put("mail.smtp.port", port);
                props.put("mail.smtp.starttls.enable", "true");

                l_session = Session.getInstance(props,
                        new javax.mail.Authenticator() {

                            protected PasswordAuthentication getPasswordAuthentication() {
                                return new PasswordAuthentication(SMTP_AUTH_USER, SMTP_AUTH_PWD);
                            }
                        });

                l_session.setDebug(true); // Enable the debug mode
                result = 1;
                //sendmail gmail    
            } else {
                Properties props = new Properties();

                props.put("mail.transport.protocol", "smtps");
                props.put("mail.smtp.host", SMTP_HOST_NAME);
                props.put("mail.smtps.auth", "true");
                props.put("mail.smtp.starttls.enable", "true");
                props.put("mail.smtps.from", "kakaka@machine");

                Session mailSession = Session.getInstance(props);
                mailSession.setDebug(true);
                Transport transport = mailSession.getTransport();
                System.out.append("---------------1\n");
                transport.connect(SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD);
                System.out.append("---------------2\n");
                result = 1;
            }
        } catch (Exception e) {
            System.err.println("D:- error from checkMail: " + e.getMessage());
            result = 0;
        }
        return result;
    }

    public void updateQ000() {
        Q000Store q000store = new Q000Store();
        try {
            int check = checkMail(QV001, QV002);
            if (check == 1) {
                System.out.println("D:- ( " + getLogin().getModule() + " , " + getLogin().getCompanyNo() + " , " + PQ000 + " , " + getLogin().getId() + " , " + QV001 + " , " + QV002 + " , " + null + " , " + 0 + " , " + getLogin().getUserName() + " )");
                int row = q000store.updateQ000(getLogin().getModule(), getLogin().getCompanyNo(), PQ000, getLogin().getId(), QV001, QV002, null, 0, getLogin().getUserName());
                if (row == 0) {
                    showGlobalReport(true, getResourceString("datasuccessfail"));
                } else {
                    showGlobalReport(true, getResourceString("datasavesuccessful"));
                }
            } else {
                showGlobalReport(true, getResourceString("mailNotFound"));
            }

        } catch (Exception e) {
            System.out.println("D:- error from updateQ000: " + e.getMessage());
            showGlobalReport(true, getResourceString("datasavesuccessful"));
        }
        sendRedirectUrlTab("myprofile.jsp?fn100M=" + pn100 + "&linkfref=" + Util.convertMD5(getRequest().getRequestURI()));
    }

    public void updateQ100ByPass() {
        if (pn100 != 0) {
            q100Store = new Q100Store();
            int count = q100Store.updateQ100ById(getLogin().getId(), getLogin().getUserName(), Util.convertMD5(passowrd), Util.convertMD5(passwordCurrent), getLogin().userName);
            if (count == 0) {
                showGlobalReport(true, getResourceString("datasuccessfail"));
            } else {
                showGlobalReport(true, getResourceString("datasavesuccessful"));
            }
        }
        sendRedirectUrlTab("myprofile.jsp?fn100M=" + pn100 + "&linkfref=" + Util.convertMD5(getRequest().getRequestURI()));
    }

    public void updateGooglemail() throws Exception {
        if (pn100 != 0) {
            q100Store = new Q100Store();
            int count = q100Store.updateGoogleAccountById(getLogin().getId(), getLogin().getCompanyNo(), qv117, qv118, getLogin().userName);
            if (count == 0) {
                showGlobalReport(true, getResourceString("datasuccessfail"));
            } else {
                showGlobalReport(true, getResourceString("datasavesuccessful"));
            }
        }

//        System.out.println("D:- qv117: " + qv117 + "  qv118: " + qv118);
//
//        String xform = "DES/ECB/PKCS5Padding";
//        // Generate a secret key
//        KeyGenerator kg = KeyGenerator.getInstance("DES");
//        kg.init(56); // 56 is the keysize. Fixed for DES
//        SecretKey key = kg.generateKey();
//
//        byte[] dataBytes =qv118.getBytes();
//
//        Crypto crypt = new Crypto();
//        System.out.println("D:- first: " + qv118);
//        byte[] encBytes = crypt.encrypt(dataBytes, key, xform);
//        System.out.println("D:- encrypt: " + encBytes);
//        System.out.println("D:- encrypt: " + new String(encBytes));
//        byte[] decBytes = crypt.decrypt(encBytes, key, xform);
//        System.out.println("D:- decrypt: " +decBytes);
//        System.out.println("D:- decrypt: " +new String(decBytes));
//
//        boolean expected = java.util.Arrays.equals(dataBytes, decBytes);
//        System.out.println("Test " + (expected ? "SUCCEEDED!" : "FAILED!"));

        sendRedirectUrlTab("myprofile.jsp?fn100M=" + pn100 + "&linkfref=" + Util.convertMD5(getRequest().getRequestURI()));

    }

    public void updateGooglemailReceive() throws Exception {
        if (pn100 != 0) {
            q100Store = new Q100Store();
            int count = q100Store.updateGoogleAccountReceiveById(getLogin().getId(), getLogin().getCompanyNo(), qv119, qv120, getLogin().userName);
            if (count == 0) {
                showGlobalReport(true, getResourceString("datasuccessfail"));
            } else {
                showGlobalReport(true, getResourceString("datasavesuccessful"));
            }
        }
        sendRedirectUrlTab("myprofile.jsp?fn100M=" + pn100 + "&linkfref=" + Util.convertMD5(getRequest().getRequestURI()));
    }

    public void updateSignature() throws Exception {
        if (pn100 != 0) {
            q100Store = new Q100Store();
            int count = q100Store.updateSignature(getLogin().getId(), getLogin().getCompanyNo(), qv121, getLogin().userName);
            if (count == 0) {
                showGlobalReport(true, getResourceString("datasuccessfail"));
            } else {
                showGlobalReport(true, getResourceString("datasavesuccessful"));
            }
        }
        sendRedirectUrlTab("myprofile.jsp?fn100M=" + pn100 + "&linkfref=" + Util.convertMD5(getRequest().getRequestURI()));
    }

    public List<Q100> getListTabQ100() {
        try {
            if (pn100 != 0) {
                q100Store = new Q100Store();
                listQ100 = q100Store.getListTabQ100(pn100, getLogin().userName);
                if (getListQ100().size() > 0) {
                    this.passowrd = getListQ100().get(0).getPassword();
                    this.timezone = getListQ100().get(0).getQv114();
                    this.language = getListQ100().get(0).getQv115();
                    this.money = getListQ100().get(0).getDevice();
                    this.fomatdate = getListQ100().get(0).getQv116();
                    this.qv117 = getListQ100().get(0).getQv117();
                    this.qv118 = getListQ100().get(0).getQv118();
                    this.qv119 = getListQ100().get(0).getQv119();
                    this.qv120 = getListQ100().get(0).getQv120();
                    this.qv121 = getListQ100().get(0).getQv121();

                } else {
                    // this.pn100 = pn1000;
                }
            }
            return getListQ100();
        } catch (Exception ex) {
            System.out.println(ex);
            return null;
        }
    }
//    public List<Q100Controller> getListTabQ1001() {
//          List<Q100Controller> listQ100Controller = new ArrayList<Q100Controller>();
//        try {
//          
//            if (pn100 != 0) {
//                q100Store = new Q100Store();
//                listQ100 = q100Store.getListTabQ100(pn100, getLogin().userName);
//               
//            }
//            Iterator ic = listQ100.iterator();
//            while(ic.hasNext()){
//                Q100 q = (Q100)ic.next();
//                Q100Controller q100C = new Q100Controller();
//                String st = "";
//                if(q.getQv115().equals("vi"))
//                {
//                 st ="Việt Nam"   ;
//                }else if(q.getQv115().equals("en")){
//                     st ="English"   ;
//                }
//                else
//                {
//                    st="Deutsch";
//                }
//                
//                q100C.setLanguage(st);
//                q100C.setTimezone(q.getQv114());
//                q100C.setFomatdate(q.getQv116());
//                listQ100Controller.add(q100C);
//                
//            }
//            
//            return listQ100Controller;
//        } catch (Exception ex) {
//            System.out.println(ex);
//            return null;
//        }
//    }

    /**
     * @return the q100Inf
     */
    public Q100Inf getQ100Inf() {
        return q100Inf;
    }

    /**
     * @param q100Inf the q100Inf to set
     */
    public void setQ100Inf(Q100Inf q100Inf) {
        this.q100Inf = q100Inf;
    }

    /**
     * @return the userLogin
     */
    public String getUserLogin() {
        return userLogin;
    }

    /**
     * @param userLogin the userLogin to set
     */
    public void setUserLogin(String userLogin) {
        this.userLogin = userLogin;
    }

    /**
     * @return the userLoginCheckTrue
     */
    public String getUserLoginCheckTrue() {
        return userLoginCheckTrue;
    }

    /**
     * @param aUserLoginCheckTrue the userLoginCheckTrue to set
     */
    public void setUserLoginCheckTrue(String aUserLoginCheckTrue) {
        userLoginCheckTrue = aUserLoginCheckTrue;
    }

    /**
     * @return the message
     */
    public String getMessage() {
        return message;
    }

    /**
     * @param message the message to set
     */
    public void setMessage(String message) {
        this.message = message;
    }

    /**
     * @return the passowrd
     */
    public String getPassowrd() {
        return passowrd;
    }

    /**
     * @param passowrd the passowrd to set
     */
    public void setPassowrd(String passowrd) {
        this.passowrd = passowrd;
    }

    /**
     * @return the repassword
     */
    public String getRepassword() {
        return repassword;
    }

    /**
     * @param repassword the repassword to set
     */
    public void setRepassword(String repassword) {
        this.repassword = repassword;
    }

    /**
     * @return the pn100
     */
    public int getPn100() {
        return pn100;
    }

    /**
     * @param pn100 the pn100 to set
     */
    public void setPn100(int pn100) {
        this.pn100 = pn100;
    }

    /**
     * @return the fomatdate
     */
    public String getFomatdate() {
        return fomatdate;
    }

    /**
     * @param fomatdate the fomatdate to set
     */
    public void setFomatdate(String fomatdate) {
        this.fomatdate = fomatdate;
    }

    /**
     * @return the language
     */
    public String getLanguage() {
        return language;
    }

    /**
     * @param language the language to set
     */
    public void setLanguage(String language) {

        this.language = language;
    }

    /**
     * @return the timezone
     */
    public String getTimezone() {
        return timezone;
    }

    /**
     * @param timezone the timezone to set
     */
    public void setTimezone(String timezone) {
        this.timezone = timezone;
    }

    /**
     * @return the avatar
     */
    public String getAvatar() {

        return avatar;
    }

    /**
     * @param avatar the avatar to set
     */
    public void setAvatar(String avatar) {
        this.avatar = avatar;
    }

    /**
     * @return the pm650
     */
    public int getPm650() {
        M650Store attachmentStore = new M650Store();
        avatar = "../images/avatar2.jpg";
        List<M650> listdocument = new ArrayList<M650>();
        System.out.println("size of list....." + loginSession.getLogin().getModule());
        try {

            listdocument = attachmentStore.findM650(loginSession.getLogin().getModule(), loginSession.getLogin().getCompanyNo(), 0, null, 0, 0, 0, null, "M650", 0, pn100, null, null, 0, 10000, 0, 0, loginSession.getLogin().getUserName());
            System.out.println("size of list......." + listdocument.size());

        } catch (Exception e) {
            System.out.println("error database" + e.getMessage());
        }
        for (int i = 0; i < listdocument.size(); i++) {
            if (listdocument.get(i).getMv660() != null && listdocument.get(i).getMv660().contains("A")) {
                avatar = ResourcesProvider.getDownloadFolder(listdocument.get(0).getMv653());
                pm650 = listdocument.get(i).getPm650();
                listdocument.remove(i);
                break;
            }
        }
        return pm650;
    }

    /**
     * @param pm650 the pm650 to set
     */
    public void setPm650(int pm650) {
        this.pm650 = pm650;
    }

    /**
     * @return the passwordCurrent
     */
    public String getPasswordCurrent() {
        return passwordCurrent;
    }

    /**
     * @param passwordCurrent the passwordCurrent to set
     */
    public void setPasswordCurrent(String passwordCurrent) {
        this.passwordCurrent = passwordCurrent;
    }

    /**
     * @return the test
     */
    public int getTest() {
        return test;
    }

    /**
     * @param test the test to set
     */
    public void setTest(int test) {
        this.test = test;
    }

    /**
     * @return the listQ100
     */
    public List<Q100> getListQ100() {
        return listQ100;
    }

    /**
     * @param listQ100 the listQ100 to set
     */
    public void setListQ100(List<Q100> listQ100) {
        this.listQ100 = listQ100;
    }

    /**
     * @return the money
     */
    public String getMoney() {
        return money;
    }

    /**
     * @param money the money to set
     */
    public void setMoney(String money) {
        this.money = money;
    }

    /**
     * @return the qv117
     */
    public String getQv117() {
        return qv117;
    }

    /**
     * @param qv117 the qv117 to set
     */
    public void setQv117(String qv117) {
        this.qv117 = qv117;
    }

    /**
     * @return the qv118
     */
    public String getQv118() {
        return qv118;
    }

    /**
     * @param qv118 the qv118 to set
     */
    public void setQv118(String qv118) {
        this.qv118 = qv118;
    }

    /**
     * @return the qv119
     */
    public String getQv119() {
        return qv119;
    }

    /**
     * @param qv119 the qv119 to set
     */
    public void setQv119(String qv119) {
        this.qv119 = qv119;
    }

    /**
     * @return the qv120
     */
    public String getQv120() {
        return qv120;
    }

    /**
     * @param qv120 the qv120 to set
     */
    public void setQv120(String qv120) {
        this.qv120 = qv120;
    }

    /**
     * @return the qv121
     */
    public String getQv121() {
        return qv121;
    }

    /**
     * @param qv121 the qv121 to set
     */
    public void setQv121(String qv121) {
        this.qv121 = qv121;
    }

    /**
     * @return the FN100
     */
    public int getFN100() {
        return FN100;
    }

    /**
     * @param FN100 the FN100 to set
     */
    public void setFN100(int FN100) {
        this.FN100 = FN100;
    }

    /**
     * @return the PQ000
     */
    public int getPQ000() {
        return PQ000;
    }

    /**
     * @param PQ000 the PQ000 to set
     */
    public void setPQ000(int PQ000) {
        this.PQ000 = PQ000;
    }

    /**
     * @return the QV001
     */
    public String getQV001() {
        return QV001;
    }

    /**
     * @param QV001 the QV001 to set
     */
    public void setQV001(String QV001) {
        this.QV001 = QV001;
    }

    /**
     * @return the QV002
     */
    public String getQV002() {
        return QV002;
    }

    /**
     * @param QV002 the QV002 to set
     */
    public void setQV002(String QV002) {
        this.QV002 = QV002;
    }
}
